<template>
  <div style="padding: 10px; background-color: white">
    <Search @submit="handleSearch" @reset="handleReset">
      <AFormItem label="商品编码">
        <AInput allow-clear v-model:value="state.formData.goodsCode"></AInput>
      </AFormItem>
      <AFormItem label="商品名称">
        <AInput allow-clear v-model:value="state.formData.goodsName"></AInput>
      </AFormItem>
      <AFormItem label="商品品类">
        <ASelect allow-clear v-model:value="state.formData.categoryId" :options="goodsCategoryListOptions"></ASelect>
      </AFormItem>
      <AFormItem label="商品状态">
        <ASelect allow-clear v-model:value="state.formData.status" :options="GoodsStatusOptions"> </ASelect>
      </AFormItem>
      <AFormItem label="商品条码">
        <AInput allow-clear v-model:value="state.formData.barcode"></AInput>
      </AFormItem>
    </Search>
  </div>
  <div style="padding: 10px; margin-top: 10px; background-color: white">
    <div class="mb-10">
      <AButton v-if="!props.isInModal" type="primary" :currentGoods="state.currentGoods" @click="addGoods">新增</AButton>
    </div>
    <ATable :data-source="state.dataSource" :columns="columns" bordered :pagination="false">
      <template #bodyCell="{ record, column }">
        <template v-if="column.dataIndex == 'pageUrl'">
          {{ `/pages/goodsDetail/index?goodsCode=${record.goodsCode}` }}
        </template>
        
        <template v-if="column.dataIndex == 'actions'">
          <a-button v-if="[GoodsStatusEnum.TOBEREVIEWED, GoodsStatusEnum.REJECT, GoodsStatusEnum.REVIEWED, GoodsStatusEnum.OFFSALE].includes(record.status)" type="text" @click="editGoods(record)"
            >编辑</a-button
          >
          <a-button v-else type="text" @click="detailGoods(record)">详情</a-button>
          <!-- 待审核->审核 -->
          <a-dropdown v-if="record.status === GoodsStatusEnum.TOBEREVIEWED">
            <template #overlay>
              <a-menu>
                <a-menu-item key="1">
                  <div @click="updateGoodsStatus(record.goodsCode, GoodsStatusEnum.REVIEWED)">同意</div>
                </a-menu-item>
                <a-menu-item key="2">
                  <div @click="updateGoodsStatus(record.goodsCode, GoodsStatusEnum.REJECT)">驳回</div>
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>
              审核
              <DownOutlined />
            </a-button>
          </a-dropdown>
          <!-- 已审核|下架->上架 -->
          <a-button v-if="[GoodsStatusEnum.REVIEWED, GoodsStatusEnum.OFFSALE].includes(record.status)" type="text" @click="updateGoodsStatus(record.goodsCode, GoodsStatusEnum.ONSALE)">上架</a-button>
          <!-- 上架->下架 -->
          <a-button v-if="record.status === GoodsStatusEnum.ONSALE" type="text" @click="updateGoodsStatus(record.goodsCode, GoodsStatusEnum.OFFSALE)">下架</a-button>
          <!-- 下架->作废 -->
          <a-button v-if="record.status === GoodsStatusEnum.OFFSALE" type="text" @click="updateGoodsStatus(record.goodsCode, GoodsStatusEnum.VOIDED)">作废</a-button>

          <a-popconfirm title="确认删除该商品?" v-if="[GoodsStatusEnum.TOBEREVIEWED, GoodsStatusEnum.REJECT].includes(record.status)" @confirm="deleteGoods(record.goodsCode)">
            <a-button type="text">删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </ATable>
    <Pagination :pagination="state.pagination" @change="pageChange"></Pagination>
  </div>
  <GoodsModal :is-detail="state.isDetail" :current-goods="state.currentGoods" v-if="state.goodsModalVisibel" @cancel="cancelGoodsModal" @ok="goodsModalOk"></GoodsModal>
</template>
<script lang="ts" setup>
import { reactive, h, onMounted, computed } from 'vue';
import Search from '@/components/Search/Search.vue';
import Pagination from '@/components/Pagination/index.vue';
import { GoodsTypes, CommontTypes, PageResult, ResponseVo, GoodsStatusOptions, GoodsStatusEnum, GoodsTypeEnum, GoodsCategoryTypes } from '@/type';
import { GoodsCategoryService, GoodsService } from '@/service';
import GoodsModal from './components/GoodsModal.vue';
import { Button, message } from 'ant-design-vue';
import useGoods from './hooks/useGoods';

const state = reactive<{
  formData: GoodsTypes.PageGoodsType;
  pagination: CommontTypes.IPagination;
  dataSource: GoodsTypes.IGoodsItem[];
  goodsModalVisibel: boolean;
  currentGoods: Partial<GoodsTypes.IGoodsItem>;
  isDetail: boolean;
}>({
  formData: {},
  pagination: {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  },
  dataSource: [],
  goodsModalVisibel: false,
  currentGoods: {},
  isDetail: false,
});

const { goodsCategoryListOptions } = useGoods();

const props = defineProps<{
  isInModal: boolean;
}>();

const columns = computed(() => {
  let list = [
    { title: '商品名称', dataIndex: 'goodsName' },
    { title: '商品编码', dataIndex: 'goodsCode' },
   
    {
      title: '商品类型',
      dataIndex: 'type',
      customRender({ record }: { record: GoodsTypes.IGoodsItem }) {
        if (record.type === GoodsTypeEnum.THING) return '实物';
        if (record.type === GoodsTypeEnum.SERVICE) return '服务';
      },
    },
    {
      title: '商品品类',
      dataIndex: 'categoryId',
      customRender({ record }: { record: GoodsTypes.IGoodsItem }) {
        return goodsCategoryListOptions.value.find((category) => category.value == record.categoryId)?.label;
      },
    },
    {
      title: '是否是热销商品',
      dataIndex: 'isHot',
      customRender({ record }: { record: GoodsTypes.IGoodsItem }) {
        if (record.isHot === 0) return '否';
        if (record.isHot === 1) return '是';
      },
    },
    // {title:"商品条码",dataIndex:"barcode"},
    {
      title: '商品状态',
      dataIndex: 'status',
      customRender({ record }: { record: GoodsTypes.IGoodsItem }) {
        return h('div', {}, GoodsStatusOptions.find((option) => option.value == record.status)?.label);
      },
    },
    {
      title: '创建人',
      customRender: ({ record }: { record: GoodsTypes.IGoodsItem }) => {
        return h('div', {}, `${record.creator}/${record.createTime}`);
      },
    },
    {
      title: '修改人',
      customRender: ({ record }: { record: GoodsTypes.IGoodsItem }) => {
        return h('div', {}, record.updator ? `${record.updator}/${record.updateTime}` : '-');
      },
    },
  ];
  if (!props.isInModal) {
    list.push({ title: '页面路径', dataIndex: 'pageUrl' });
    list.push({ title: '操作', dataIndex: 'actions' });
  }
  return list;
});

onMounted(() => {
  handleSearch();
});

const handleSearch = async () => {
  const res: ResponseVo<PageResult<GoodsTypes.IGoodsItem>> = await GoodsService.pageGoods({ ...state.formData, ...state.pagination });
  if (res.code === 0) {
    state.dataSource = res.data.list;
    state.pagination.total = res.data.total;
  }
};

const pageChange = (page: number, size: number) => {
  state.pagination.pageNum = page;
  state.pagination.pageSize = size;
  handleSearch();
};

const handleReset = () => {
  state.formData = {};
  state.pagination.pageNum = 1;
  state.pagination.total = 0;
  handleSearch();
};

const addGoods = () => {
  state.goodsModalVisibel = true;
  state.currentGoods = {};
  state.isDetail = false;
};

const editGoods = async (record: GoodsTypes.IGoodsItem) => {
  state.currentGoods = {};
  await detailGoods(record);
  state.isDetail = false;
};

const detailGoods = async (record: GoodsTypes.IGoodsItem) => {
  state.isDetail = true;
  let res: ResponseVo<GoodsTypes.IGoodsItem> = await GoodsService.detailGoods(record.goodsCode);
  if (res.code === 0) {
    state.currentGoods = { ...res.data };
    console.log('state.currentGoods--->', state.currentGoods);
    state.goodsModalVisibel = true;
  }
};

const updateGoodsStatus = async (goodsCode: number, status: GoodsStatusEnum) => {
  let res: ResponseVo<any> = await GoodsService.updateGoodsStatus(goodsCode, status);
  if (res.code === 0) {
    message.success('操作成功！');
    handleSearch();
  }
};

const deleteGoods = async (goodsCode: number) => {
  let res: ResponseVo<any> = await GoodsService.deleteGoods(goodsCode);
  if (res.code === 0) {
    message.success('操作成功！');
    state.pagination.pageNum = 1;
    handleSearch();
  }
};

const cancelGoodsModal = () => {
  state.goodsModalVisibel = false;
};

const goodsModalOk = () => {
  state.goodsModalVisibel = false;
  state.pagination.pageNum = 1;
  handleSearch();
};
</script>
<style lang="ts" setup></style>
